import pandas as pd
import random
import os
import sys
from datetime import datetime, timedelta
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from openpyxl.styles import Font, Alignment, Border, Side
from openpyxl.utils import get_column_letter

# 确保编码设置正确，解决中文显示问题
import locale
try:
    # 尝试设置系统默认编码为UTF-8，兼容不同Windows版本
    locale.setlocale(locale.LC_ALL, 'zh_CN.UTF-8')
except:
    try:
        locale.setlocale(locale.LC_ALL, 'Chinese_PRC.936')
    except:
        try:
            # 使用系统默认区域设置作为最后的选择
            locale.setlocale(locale.LC_ALL, '')
        except Exception as e:
            print(f"设置区域设置失败: {e}")

# 延迟导入pandas，确保更好的兼容性
def import_pandas():
    """延迟导入pandas并配置以确保在各Windows版本上的兼容性"""
    try:
        import pandas as pd
        # 配置pandas以使用openpyxl引擎，确保更好的Excel兼容性
        pd.options.io.excel.xlsx.writer = 'openpyxl'
        pd.options.future.infer_string = False  # 禁用可能不兼容的新特性
        
        # 额外的兼容性设置
        pd.set_option('display.max_columns', None)
        pd.set_option('display.max_rows', None)
        pd.set_option('display.width', 1000)
        pd.set_option('compute.use_bottleneck', False)  # 禁用可能在旧系统上不兼容的加速
        pd.set_option('compute.use_numba', False)  # 禁用可能在旧系统上不兼容的加速
        
        return pd
    except ImportError:
        print("无法导入pandas库，程序将使用简化功能")
        return None

# 提前导入pandas
pd = import_pandas()

# 检查Windows版本以优化兼容性
import platform

# 获取Windows版本信息
windows_version = platform.system()
windows_build = platform.win32_ver()[1] if windows_version == 'Windows' else ''

# 定义兼容性设置
class WindowsCompatibility:
    """Windows多版本兼容性设置"""
    def __init__(self):
        # 检测Windows版本
        self.is_win7 = False
        self.is_win10_11 = False
        
        if windows_version == 'Windows':
            try:
                build_num = int(windows_build)
                # Windows 7: 6.1.*, Windows 10: 10.0.10240+, Windows 11: 10.0.22000+
                if build_num >= 22000:
                    self.is_win10_11 = True  # Windows 11
                elif build_num >= 10240:
                    self.is_win10_11 = True  # Windows 10
                elif build_num >= 7600:
                    self.is_win7 = True  # Windows 7
            except:
                print("无法准确检测Windows版本，使用通用设置")
                
    def get_optimal_settings(self):
        """获取当前系统的最佳设置"""
        settings = {
            'file_path_encoding': 'utf-8',
            'max_image_size': 1000000,  # 100万像素
            'font_family': '微软雅黑',
            'font_size': 10
        }
        
        if self.is_win7:
            # Windows 7特定优化
            settings['font_family'] = 'SimHei'
            settings['font_size'] = 9
        elif self.is_win10_11:
            # Windows 10/11特定优化
            settings['font_size'] = 10
        
        return settings

# 初始化兼容性设置
compatibility = WindowsCompatibility()
comp_settings = compatibility.get_optimal_settings()


class CanteenMenuSystem:
    def __init__(self):
        self._initialize_dish_categories()
        self.dish_database_file = 'dish_database.xlsx'
        
        # 食材关联规则 - 避免同一天出现相关联的食材
        self.ingredient_rules = {
            '番茄': ['番茄', '西红柿'],
            '牛肉': ['牛肉', '牛排', '牛腩', '牛尾', '泡椒牛肉'],
            '猪肉': ['猪肉', '五花肉', '排骨', '猪耳朵', '卤肉', '白肉'],
            '鸡肉': ['鸡肉', '鸡', '鸡翅', '辣子鸡', '宫保鸡丁'],
            '土豆': ['土豆', '马铃薯', '洋芋', '土豆丝', '土豆泥'],
            '茄子': ['茄子'],
            '黄瓜': ['黄瓜'],
            '白菜': ['白菜', '小白菜', '大白菜'],
            '萝卜': ['萝卜', '胡萝卜'],
            '海带': ['海带', '带丝'],
            '青菜': ['青菜', '小青菜', '瓢儿菜'],
            '豆腐': ['豆腐', '豆干']
        }
        
        # 初始化时自动加载数据库
        self.db_loaded = False
        self.load_database()  # 自动加载数据

    def _initialize_dish_categories(self):
        """初始化菜品分类"""
        self.dish_categories = {
            '早餐': {
                '主食': [],
                '饮品': [],
                '其他': [],
                '米粉': []
            },
            '荤菜': {
                '猪肉': [],
                '牛肉': [],
                '鸡肉': []
            },
            '素菜': [],
            '汤类': {
                '荤汤': [],
                '素汤': []
            },
            '水果': [],
            '简餐': []
        }

    def load_database(self):
        """加载菜品数据库，增强兼容性处理"""
        try:
            # 定义多个可能的数据库文件位置
            possible_paths = [
                # 1. 当前工作目录
                self.dish_database_file,
                # 2. 脚本所在目录
                os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), self.dish_database_file)),
                # 3. 对于编译后的程序，检查当前运行目录
                os.path.abspath(os.path.join(os.getcwd(), self.dish_database_file))
            ]
            
            # 寻找存在的数据库文件
            database_path = None
            for path in possible_paths:
                if os.path.exists(path):
                    database_path = path
                    break
            
            if database_path:
                print(f"找到数据库文件: {database_path}")
                # 尝试从现有文件加载
                if pd is not None:
                    try:
                        df = pd.read_excel(database_path, sheet_name=None)
                        
                        # 遍历所有分类加载数据
                        for category in self.dish_categories:
                            if category in df:
                                cat_df = df[category]
                                if isinstance(self.dish_categories[category], dict):
                                    for sub_cat in self.dish_categories[category]:
                                        if sub_cat in cat_df.columns:
                                            items = cat_df[sub_cat].dropna().tolist()
                                            if items:
                                                self.dish_categories[category][sub_cat] = items
                                else:
                                    if category in cat_df.columns:
                                        items = cat_df[category].dropna().tolist()
                                        if items:
                                            self.dish_categories[category] = items
                        
                        # 数据清理
                        if '简餐' in self.dish_categories:
                            self.dish_categories['简餐'] = ['豌杂面' if item == '面条' else item 
                                                          for item in self.dish_categories['简餐']]
                            self.dish_categories['简餐'] = [item for item in self.dish_categories['简餐'] if item != '炒饭']
                        
                        if '主食' in self.dish_categories['早餐']:
                            self.dish_categories['早餐']['主食'] = [
                                item for item in self.dish_categories['早餐']['主食'] 
                                if item != '炒饭'
                            ]
                        
                        self._ensure_breakfast_staples()
                    except Exception as e:
                        print(f"使用pandas加载数据库失败: {e}")
                        # 加载失败时使用默认数据
                        self._add_default_homemade_dishes()
                else:
                    # 如果没有pandas，直接使用默认数据
                    print("pandas不可用，使用默认数据库")
                    self._add_default_homemade_dishes()
            else:
                # 文件不存在，使用默认数据
                self._add_default_homemade_dishes()
            
            self.db_loaded = True
            return True
        except Exception as e:
            print(f"加载菜品数据库出错: {e}")
            # 出错时确保至少有默认数据可用
            try:
                self._add_default_homemade_dishes()
                self.db_loaded = True
                return True
            except Exception:
                self.db_loaded = False
                return False

    def _ensure_breakfast_staples(self):
        """确保早餐包含荞饼和粗粮"""
        required_staples = ['荞饼', '粗粮']
        for staple in required_staples:
            if staple not in self.dish_categories['早餐']['主食']:
                self.dish_categories['早餐']['主食'].append(staple)
        self.dish_categories['早餐']['主食'] = list(set(self.dish_categories['早餐']['主食']))

    def _check_database_validity(self):
        """检查数据库有效性"""
        required_categories = ['早餐', '荤菜', '素菜', '汤类', '水果', '简餐']
        for cat in required_categories:
            if cat not in self.dish_categories:
                return False
        
        if '米粉' not in self.dish_categories['早餐']:
            return False
            
        return True

    def _add_default_rice_noodles(self):
        """添加默认米粉种类"""
        self.dish_categories['早餐']['米粉'] = [
            '红烧牛肉粉', '酸菜肉丝粉', '排骨粉',
            '泡椒鸡杂粉', '蹄花粉', '香菇臊子粉'
        ]

    def _add_default_simple_meals(self):
        """添加默认简餐（包含具体炒饭种类）"""
        self.dish_categories['简餐'] = [
            # 具体的炒饭种类
            '蛋炒饭', '青椒肉丝炒饭', '榨菜炒饭', 
            '扬州炒饭', '火腿蛋炒饭', '老干妈炒饭',
            # 其他简餐
            '豌杂面', '鸡火丝饵块', '炒河粉',
            '大碗宽面', '红烧牛肉面'
        ]

    def _add_default_homemade_dishes(self):
        """添加默认菜品数据"""
        # 早餐
        self.dish_categories['早餐']['主食'] = [
            '馒头', '花卷', '包子', '稀饭',
            '面条', '鸡火丝饵块', '炒河粉',
            '荞饼', '粗粮'
        ]
        
        self.dish_categories['早餐']['饮品'] = [
            '牛奶', '酸奶'
        ]
        
        self.dish_categories['早餐']['其他'] = [
            '鸡蛋', '小菜', '咸菜'
        ]
        
        # 添加默认米粉种类
        self._add_default_rice_noodles()

        # 添加简餐（包含具体炒饭种类）
        self._add_default_simple_meals()

        # 猪肉类
        self.dish_categories['荤菜']['猪肉'] = [
            '红烧肉', '回锅肉', '鱼香肉丝', '青椒肉丝',
            '宫保肉丁', '水煮肉片', '糖醋排骨', '东坡肉',
            '蒜苔炒肉', '梅菜扣肉', '京酱肉丝', '木须肉'
        ]

        # 牛肉类
        self.dish_categories['荤菜']['牛肉'] = [
            '青椒牛肉', '红烧牛肉', '土豆炖牛肉', '小炒黄牛肉',
            '水煮牛肉', '番茄炖牛肉', '香煎牛排'
        ]

        # 鸡肉类
        self.dish_categories['荤菜']['鸡肉'] = [
            '宫保鸡丁', '辣子鸡', '黄焖鸡', '香菇滑鸡',
            '大盘鸡', '可乐鸡翅'
        ]

        # 素菜
        self.dish_categories['素菜'] = [
            '炒凤尾', '炒莲花白', '炒土豆丝', '炒洋茄瓜',
            '蒜蓉西兰花', '麻婆豆腐', '凉拌黄瓜', '醋溜土豆丝',
            '红烧茄子', '干煸豆角', '手撕包菜', '清炒空心菜',
            '蒜蓉油麦菜', '凉拌海带丝', '地三鲜', '炒青菜'
        ]

        # 汤类
        self.dish_categories['汤类']['荤汤'] = [
            '冬瓜排骨汤', '玉米排骨汤', '萝卜炖排骨汤',
            '海带炖鸡汤', '番茄牛尾汤'
        ]
        
        self.dish_categories['汤类']['素汤'] = [
            '番茄鸡蛋汤', '紫菜蛋花汤', '青菜豆腐汤', 
            '元根酸菜土豆汤', '酸菜粉丝汤', '黄瓜皮蛋汤',
            '海带汤', '冬瓜汤', '番茄汤', '丝瓜汤'
        ]

        # 水果 - 只保留时令水果，方便后期添加
        self.dish_categories['水果'] = ['时令水果']

    def _save_dish_database(self):
        """保存菜品数据库到Excel文件"""
        try:
            with pd.ExcelWriter(self.dish_database_file, engine='openpyxl') as writer:
                for category, sub_categories in self.dish_categories.items():
                    if isinstance(sub_categories, dict):
                        max_length = max(len(items) for items in sub_categories.values()) if sub_categories else 0
                        normalized_data = {}
                        for key, items in sub_categories.items():
                            normalized_list = items.copy()
                            while len(normalized_list) < max_length:
                                normalized_list.append("")
                            normalized_data[key] = normalized_list
                        sub_df = pd.DataFrame(normalized_data)
                    else:
                        sub_df = pd.DataFrame({category: sub_categories})
                    sub_df.to_excel(writer, sheet_name=category, index=False)
                
                # 设置所有工作表的列宽
                for sheet_name in writer.sheets:
                    worksheet = writer.sheets[sheet_name]
                    for col in range(1, worksheet.max_column + 1):
                        col_letter = get_column_letter(col)
                        worksheet.column_dimensions[col_letter].width = 15
            
            return True
        except Exception as e:
            print(f"保存Excel数据库出错: {e}")
            return False

    def _extract_ingredients(self, dish_name):
        """从菜名中提取主要食材"""
        ingredients = set()
        for key, related in self.ingredient_rules.items():
            for ingredient in related:
                if ingredient in dish_name:
                    ingredients.add(key)
                    break
        return ingredients

    def _check_dish_conflict(self, dish_name, used_dishes, used_ingredients):
        """检查菜品是否与已使用菜品或食材冲突"""
        # 检查是否重复菜品
        if dish_name in used_dishes:
            return True
            
        # 检查食材冲突
        dish_ingredients = self._extract_ingredients(dish_name)
        for ingredient in dish_ingredients:
            if ingredient in used_ingredients:
                return True
                
        return False

    def _select_breakfast_staple(self, used_dishes, used_ingredients):
        """选择早餐主食，确保不与已选菜品冲突"""
        # 早餐主食分组（避免同类同时出现）
        breakfast_staple_groups = {
            '馒头类': ['馒头', '花卷'],
            '包子类': ['包子'],
            '饼类': ['荞饼'],
            '粗粮类': ['粗粮']
        }
        
        # 过滤出可用的主食组
        available_groups = []
        for group_name, staples in breakfast_staple_groups.items():
            has_available = any(not self._check_dish_conflict(staple, used_dishes, used_ingredients) 
                               for staple in staples)
            if has_available:
                available_groups.append(group_name)
        
        if not available_groups:
            available_groups = list(breakfast_staple_groups.keys())
        
        # 随机选择一个组
        selected_group = random.choice(available_groups)
        
        # 从选择的组中随机选择一个不冲突的主食
        group_staples = breakfast_staple_groups[selected_group]
        available_staples = [s for s in group_staples 
                            if s in self.dish_categories['早餐']['主食'] 
                            and not self._check_dish_conflict(s, used_dishes, used_ingredients)]
        
        if not available_staples:
            # 如果没有完全不冲突的，至少选择不重复的
            available_staples = [s for s in group_staples 
                                if s in self.dish_categories['早餐']['主食'] 
                                and s not in used_dishes]
        
        if not available_staples:
            return "馒头"
            
        return random.choice(available_staples)

    def _generate_breakfast(self, day, week_used_dishes, daily_used_dishes, daily_used_ingredients):
        """生成早餐菜单"""
        # 早餐配置
        breakfast_config = {
            '周一': ['牛奶', '酸奶', '稀饭'],
            '周三': ['牛奶', '酸奶', '稀饭'],
            '周五': ['牛奶', '酸奶', '稀饭'],
            '周二': ['米粉'],
            '周四': ['米粉']
        }
        
        try:
            if day in breakfast_config:
                if breakfast_config[day] == ['米粉']:
                    # 使用早餐分类中的米粉列表
                    available_noodles = [n for n in self.dish_categories['早餐']['米粉'] 
                                       if not self._check_dish_conflict(n, daily_used_dishes, daily_used_ingredients)
                                       and n not in week_used_dishes]
                    
                    if not available_noodles:
                        available_noodles = [n for n in self.dish_categories['早餐']['米粉'] 
                                           if n not in week_used_dishes]
                    
                    if not available_noodles:
                        available_noodles = self.dish_categories['早餐']['米粉']
                        if not available_noodles:
                            self._add_default_rice_noodles()
                            available_noodles = self.dish_categories['早餐']['米粉']
                    
                    selected = random.choice(available_noodles)
                    daily_used_dishes.add(selected)
                    week_used_dishes.add(selected)
                    daily_used_ingredients.update(self._extract_ingredients(selected))
                    return [selected]
                else:
                    base = []
                    # 筛选不冲突的基础早餐
                    for item in breakfast_config[day]:
                        if (not self._check_dish_conflict(item, daily_used_dishes, daily_used_ingredients)
                            and item not in week_used_dishes):
                            base.append(item)
                            daily_used_dishes.add(item)
                            week_used_dishes.add(item)
                            daily_used_ingredients.update(self._extract_ingredients(item))
                    
                    # 如果没有足够的基础早餐，添加一些不冲突的
                    while len(base) < len(breakfast_config[day]):
                        for item in breakfast_config[day]:
                            if item not in base:
                                base.append(item)
                                daily_used_dishes.add(item)
                                week_used_dishes.add(item)
                                daily_used_ingredients.update(self._extract_ingredients(item))
                                break
                    
                    # 选择主食
                    staple = None
                    # 先尝试找本周未用过的主食
                    for _ in range(3):  # 尝试3次
                        potential_staple = self._select_breakfast_staple(daily_used_dishes, daily_used_ingredients)
                        if potential_staple not in week_used_dishes:
                            staple = potential_staple
                            break
                    
                    # 如果找不到本周未用过的，就找不冲突的
                    if staple is None:
                        staple = self._select_breakfast_staple(daily_used_dishes, daily_used_ingredients)
                    
                    base.append(staple)
                    daily_used_dishes.add(staple)
                    week_used_dishes.add(staple)
                    daily_used_ingredients.update(self._extract_ingredients(staple))
                    
                    # 随机添加一个"其他"类别的食品
                    available_other = [o for o in self.dish_categories['早餐']['其他'] 
                                     if not self._check_dish_conflict(o, daily_used_dishes, daily_used_ingredients)
                                     and o not in week_used_dishes]
                    
                    if not available_other:
                        available_other = [o for o in self.dish_categories['早餐']['其他'] 
                                         if o not in daily_used_dishes]
                    
                    if available_other:
                        other_item = random.choice(available_other)
                        base.append(other_item)
                        daily_used_dishes.add(other_item)
                        week_used_dishes.add(other_item)
                        daily_used_ingredients.update(self._extract_ingredients(other_item))
                    
                    return base
            return []
        except Exception as e:
            print(f"生成早餐出错: {e}")
            return ['牛奶', '稀饭', '馒头', '鸡蛋']

    def generate_menu(self, start_date, weeks=1):
        """生成菜单，跳过周六和周日"""
        # 确保数据库已加载
        if not self.db_loaded:
            return None, None, None
            
        menu_data = []
        current_date = datetime.strptime(start_date, '%Y-%m-%d')
        
        # 确保从周一（0）开始，如果不是周一，调整到下周一
        if current_date.weekday() != 0:  # 0是周一
            days_to_monday = (7 - current_date.weekday()) % 7
            current_date += timedelta(days=days_to_monday)
        
        # 生成指定周数的工作日菜单
        for week in range(weeks):
            # 每周重置肉类使用标记，确保每周各出现一次
            meat_used = {'牛肉': False, '鸡肉': False}
            # 每周跟踪已使用的菜品，确保同一周内无重复
            week_used_dishes = set()
            
            # 随机选择牛肉和鸡肉应该出现在哪两天（不包括周五，因为周五是简餐）
            # 避免牛肉和鸡肉同一天出现
            available_days = [0, 1, 2, 3]  # 0=周一, 1=周二, 2=周三, 3=周四
            
            # 选择牛肉和鸡肉的日期，确保每周各出现一次
            beef_day = random.choice(available_days)
            chicken_days = [day for day in available_days if day != beef_day]
            chicken_day = random.choice(chicken_days) if chicken_days else random.choice(available_days)
                
            # 记录本周牛肉和鸡肉的日期
            meat_days = {'牛肉': beef_day, '鸡肉': chicken_day}
            
            # 生成周一到周五的菜单
            for day_offset in range(5):  # 0=周一, 1=周二, ..., 4=周五
                # 计算当前日期
                current_day = current_date + timedelta(days=day_offset)
                day_name = ["周一", "周二", "周三", "周四", "周五"][day_offset]
                
                # 每天重置已使用菜品和食材
                daily_used_dishes = set()
                daily_used_ingredients = set()
                
                try:
                    # 早餐
                    breakfast = self._generate_breakfast(day_name, week_used_dishes, daily_used_dishes, daily_used_ingredients)

                    # 午餐 - 周五使用简餐
                    if day_offset == 4:  # 周五
                        available_meals = [m for m in self.dish_categories['简餐'] 
                                         if not self._check_dish_conflict(m, daily_used_dishes, daily_used_ingredients)
                                         and m not in week_used_dishes]
                    
                        if not available_meals:
                            available_meals = [m for m in self.dish_categories['简餐'] 
                                             if m not in week_used_dishes]
                        
                        if not available_meals:
                            available_meals = self.dish_categories['简餐']
                            if not available_meals:
                                self._add_default_simple_meals()
                                available_meals = self.dish_categories['简餐']
                        
                        lunch_desc = f"{random.choice(available_meals)}"
                        daily_used_dishes.add(lunch_desc)
                        week_used_dishes.add(lunch_desc)
                        daily_used_ingredients.update(self._extract_ingredients(lunch_desc))
                    else:
                        # 生成午餐，传递肉类日期安排和当前日期偏移
                        meat_dishes, veg_dishes, soup = self._generate_lunch(day_name, meat_used, week_used_dishes, 
                                                                           daily_used_dishes, daily_used_ingredients,
                                                                           meat_days, day_offset)
                        lunch_desc = self._format_lunch(meat_dishes, veg_dishes, soup)
                        
                        # 验证菜品总数
                        total_dishes = len(meat_dishes) + len(veg_dishes) + 1  # +1 是汤
                        if total_dishes != 5:
                            meat_dishes, veg_dishes, soup = self._adjust_lunch_dishes(meat_dishes, veg_dishes, soup, 
                                                                                    week_used_dishes, daily_used_dishes, 
                                                                                    daily_used_ingredients)
                            lunch_desc = self._format_lunch(meat_dishes, veg_dishes, soup)
                        
                        # 更新已使用菜品和食材
                        for dish in meat_dishes + veg_dishes + [soup]:
                            daily_used_dishes.add(dish)
                            week_used_dishes.add(dish)
                            daily_used_ingredients.update(self._extract_ingredients(dish))

                    # 水果
                    if self.dish_categories['水果']:
                        available_fruits = [f for f in self.dish_categories['水果']
                                          if not self._check_dish_conflict(f, daily_used_dishes, daily_used_ingredients)
                                          and f not in week_used_dishes]
                        
                        if not available_fruits:
                            available_fruits = [f for f in self.dish_categories['水果']
                                              if f not in daily_used_dishes]
                        
                        fruit = random.choice(available_fruits) if available_fruits else random.choice(self.dish_categories['水果'])
                    else:
                        fruit = "时令水果"
                    
                    # 添加水果到使用记录
                    daily_used_dishes.add(fruit)
                    week_used_dishes.add(fruit)

                    # 添加到每日菜单
                    date_str = current_day.strftime('%Y-%m-%d')
                    menu_data.append({
                        '日期': date_str,
                        '星期': day_name,
                        '早餐': ', '.join(breakfast),
                        '午餐': lunch_desc,
                        '水果': fruit
                    })

                except Exception as e:
                    print(f"生成{day_name}菜单出错: {e}")
                    date_str = current_day.strftime('%Y-%m-%d')
                    default_lunch = '红烧肉, 鱼香肉丝, 炒青菜, 麻婆豆腐, 番茄鸡蛋汤'
                    menu_data.append({
                        '日期': date_str,
                        '星期': day_name,
                        '早餐': '牛奶, 稀饭, 馒头, 鸡蛋',
                        '午餐': default_lunch,
                        '水果': '时令水果'
                    })
            
            # 移动到下一周的周一
            current_date += timedelta(days=7)

        # 计算菜单的结束日期
        if menu_data:
            end_date = menu_data[-1]['日期']
        else:
            end_date = (datetime.strptime(start_date, '%Y-%m-%d') + 
                       timedelta(days=weeks*5 - 1)).strftime('%Y-%m-%d')
        
        # 打印生成的菜单数据到控制台，用于检查
        print("\n\n生成的菜单数据：")
        print(pd.DataFrame(menu_data))
        
        return pd.DataFrame(menu_data), start_date, end_date

    def _adjust_lunch_dishes(self, meat_dishes, veg_dishes, soup, week_used, daily_used, daily_ingredients):
        """调整午餐菜品"""
        target_total = 5
        current_total = len(meat_dishes) + len(veg_dishes) + 1  # +1 是汤
        difference = target_total - current_total
        
        # 如果需要增加菜品
        while difference > 0:
            # 优先增加素菜
            if len(veg_dishes) < len(self.dish_categories['素菜']):
                available_veg = [v for v in self.dish_categories['素菜'] 
                                if not self._check_dish_conflict(v, daily_used, daily_ingredients)
                                and v not in veg_dishes
                                and v not in week_used]
                if available_veg:
                    new_veg = random.choice(available_veg)
                    veg_dishes.append(new_veg)
                    difference -= 1
                    continue
            
            # 如果无法增加素菜，则增加荤菜
            if len(meat_dishes) < 2:  # 限制最多2个荤菜
                # 检查当前已有的肉类类型
                current_meat_types = set()
                for dish in meat_dishes:
                    for meat_type in ['牛肉', '鸡肉', '猪肉']:
                        if meat_type in self._extract_ingredients(dish):
                            current_meat_types.add(meat_type)
                            break
                
                # 确定可用的肉类类型（确保牛肉和鸡肉不会同时出现）
                available_meat_types = []
                if '牛肉' in current_meat_types:
                    available_meat_types.append('猪肉')  # 如果已有牛肉，只能加猪肉
                elif '鸡肉' in current_meat_types:
                    available_meat_types.append('猪肉')  # 如果已有鸡肉，只能加猪肉
                else:
                    available_meat_types = ['猪肉', '牛肉', '鸡肉']  # 否则都可以加
                
                available_meats = []
                for meat_type in available_meat_types:
                    available_meats.extend([d for d in self.dish_categories['荤菜'][meat_type] 
                                          if not self._check_dish_conflict(d, daily_used, daily_ingredients)
                                          and d not in meat_dishes
                                          and d not in week_used])
                
                if available_meats:
                    new_meat = random.choice(available_meats)
                    meat_dishes.append(new_meat)
                    difference -= 1
                    continue
            
            # 如果无法增加任何菜品，跳出循环
            break
        
        # 如果需要减少菜品
        while difference < 0:
            # 优先减少素菜
            if len(veg_dishes) > 0:
                veg_dishes.pop()
                difference += 1
                continue
            
            # 如果没有素菜可减少，则减少荤菜
            if len(meat_dishes) > 0:
                meat_dishes.pop()
                difference += 1
                continue
            
            # 如果无法减少任何菜品，跳出循环
            break
            
        return meat_dishes, veg_dishes, soup

    def _generate_lunch(self, day, meat_used, week_used, daily_used, daily_ingredients, meat_days=None, day_offset=None):
        """生成午餐菜品组合，确保牛肉和鸡肉每周只出现一次且不会出现在同一天，且汤为肉类时荤菜总数限制为1个"""
        try:
            # 选择汤（1个） - 先选汤，因为如果汤是肉类，会影响荤菜数量
            if len(self.dish_categories['汤类']['荤汤']) == 0 and len(self.dish_categories['汤类']['素汤']) == 0:
                self._add_default_homemade_dishes()

            soup = None
            possible_soups = []
            for soup_type in ['荤汤', '素汤']:
                possible_soups.extend([s for s in self.dish_categories['汤类'][soup_type]
                                     if not self._check_dish_conflict(s, daily_used, daily_ingredients)
                                     and s not in week_used])
            
            # 检查是否是牛肉或鸡肉日，确保这些日期不选择对应肉类的汤
            if meat_days and day_offset is not None:
                if day_offset == meat_days.get('牛肉'):
                    # 牛肉日，不选择牛肉汤，以确保牛肉作为菜品出现
                    possible_soups = [s for s in possible_soups if '牛肉' not in self._extract_ingredients(s)]
                elif day_offset == meat_days.get('鸡肉'):
                    # 鸡肉日，不选择鸡肉汤，以确保鸡肉作为菜品出现
                    possible_soups = [s for s in possible_soups if '鸡肉' not in self._extract_ingredients(s)]
            
            # 过滤掉含有本周已用肉类的汤品（除了当天应该使用的肉类）
            filtered_soups = []
            for soup_candidate in possible_soups:
                soup_ingredients = self._extract_ingredients(soup_candidate)
                # 如果是牛肉日且汤有牛肉，允许使用；否则检查是否含有已用肉类
                if day_offset == meat_days.get('牛肉') and '牛肉' in soup_ingredients:
                    filtered_soups.append(soup_candidate)
                elif day_offset == meat_days.get('鸡肉') and '鸡肉' in soup_ingredients:
                    filtered_soups.append(soup_candidate)
                elif ('牛肉' not in soup_ingredients or not meat_used['牛肉']) and \
                     ('鸡肉' not in soup_ingredients or not meat_used['鸡肉']):
                    filtered_soups.append(soup_candidate)
            
            # 如果过滤后没有可用汤品，使用原始列表（不考虑当天应该使用的肉类）
            if not filtered_soups:
                filtered_soups = possible_soups
            
            if not filtered_soups:
                for soup_type in ['荤汤', '素汤']:
                    filtered_soups.extend([s for s in self.dish_categories['汤类'][soup_type]
                                         if not self._check_dish_conflict(s, daily_used, daily_ingredients)])
            
            if not filtered_soups:
                filtered_soups = []
                for soup_type in ['荤汤', '素汤']:
                    filtered_soups.extend(self.dish_categories['汤类'][soup_type])
            
            if filtered_soups:
                soup = random.choice(filtered_soups)
            else:
                soup = "番茄鸡蛋汤"
            
            # 检查汤是否为肉类，并标记肉类使用状态
            soup_ingredients = self._extract_ingredients(soup)
            
            # 全面检查是否为荤汤（包含任何肉类）
            soup_is_meat = '牛肉' in soup_ingredients or '鸡肉' in soup_ingredients or '猪肉' in soup_ingredients
            
            # 如果汤含有肉类，标记对应肉类为已使用
            # 但注意：如果是当天应该使用的肉类，不要在这里标记，以免影响菜品选择
            if '牛肉' in soup_ingredients and not (meat_days and day_offset == meat_days.get('牛肉')):
                meat_used['牛肉'] = True
            if '鸡肉' in soup_ingredients and not (meat_days and day_offset == meat_days.get('鸡肉')):
                meat_used['鸡肉'] = True
            if '猪肉' in soup_ingredients:
                meat_used['猪肉'] = True
            
            # 如果汤是肉类，设置荤菜数量为1；否则为2
            meat_count = 1 if soup_is_meat else 2
            
            # 选择肉类
            meat_dishes = []
            selected_meat_types = []
            
            # 确定可用的肉类类别，严格确保在指定日期必须使用牛肉或鸡肉，且不出现在同一天
            available_meat_categories = ['猪肉']
            if meat_days and day_offset is not None:
                # 在指定的牛肉日，必须使用牛肉
                if day_offset == meat_days.get('牛肉') and not meat_used.get('牛肉', False):
                    # 如果是牛肉日且牛肉尚未使用，则确保牛肉作为菜品出现
                    if not ('牛肉' in soup_ingredients and meat_used.get('牛肉', False)):
                        available_meat_categories = ['牛肉']  # 强制使用牛肉
                # 在指定的鸡肉日，必须使用鸡肉
                elif day_offset == meat_days.get('鸡肉') and not meat_used.get('鸡肉', False):
                    # 如果是鸡肉日且鸡肉尚未使用，则确保鸡肉作为菜品出现
                    if not ('鸡肉' in soup_ingredients and meat_used.get('鸡肉', False)):
                        available_meat_categories = ['鸡肉']  # 强制使用鸡肉
                # 如果牛肉或鸡肉已经被使用过，则不允许再次使用
                if meat_used.get('牛肉', False):
                    available_meat_categories = [m for m in available_meat_categories if m != '牛肉']
                if meat_used.get('鸡肉', False):
                    available_meat_categories = [m for m in available_meat_categories if m != '鸡肉']
            else:
                # 没有预设日期信息时的后备逻辑
                pass  # 不添加牛肉和鸡肉，避免多次出现
            
            # 确保不超过规定的荤菜数量
            while len(meat_dishes) < meat_count:
                # 随机选择肉类类型，但确保不重复使用牛肉或鸡肉
                if len(selected_meat_types) > 0:
                    # 如果已经选了牛肉或鸡肉，只能再选猪肉
                    possible_meats = [m for m in available_meat_categories 
                                     if m == '猪肉' or m not in selected_meat_types]
                else:
                    possible_meats = available_meat_categories
                
                if not possible_meats:
                    possible_meats = ['猪肉']  # 至少保证猪肉可用
                
                meat_type = random.choice(possible_meats)
                
                # 过滤可用菜品
                available_dishes = [d for d in self.dish_categories['荤菜'][meat_type] 
                                   if not self._check_dish_conflict(d, daily_used, daily_ingredients)
                                   and d not in meat_dishes
                                   and d not in week_used]
                
                if not available_dishes:
                    available_dishes = [d for d in self.dish_categories['荤菜'][meat_type] 
                                       if d not in meat_dishes
                                       and d not in week_used]
                
                if not available_dishes:
                    available_dishes = [d for d in self.dish_categories['荤菜'][meat_type] 
                                       if d not in meat_dishes]
                
                if not available_dishes:
                    self._add_default_homemade_dishes()
                    available_dishes = self.dish_categories['荤菜'][meat_type]
                
                # 选择菜品
                dish = random.choice(available_dishes)
                meat_dishes.append(dish)
                
                # 如果选择了牛肉或鸡肉，标记为已使用
                if meat_type == '牛肉':
                    meat_used['牛肉'] = True
                elif meat_type == '鸡肉':
                    meat_used['鸡肉'] = True
                    
                selected_meat_types.append(meat_type)
                
                # 安全检查，确保在指定日期成功选择了牛肉或鸡肉
                if meat_days and day_offset is not None:
                    # 检查牛肉日
                    if day_offset == meat_days.get('牛肉') and not ('牛肉' in soup_ingredients and meat_used.get('牛肉', False)):
                        # 如果是牛肉日但未通过菜品或汤使用牛肉，强制使用牛肉
                        if '牛肉' not in selected_meat_types:
                            # 查找可用的牛肉菜品
                            beef_dishes = [d for d in self.dish_categories['荤菜']['牛肉'] 
                                          if d not in meat_dishes and d not in week_used]
                            if beef_dishes:
                                # 替换最后一个非牛肉菜品，确保不超过规定的荤菜数量
                                if len(meat_dishes) > 0:
                                    meat_dishes[-1] = random.choice(beef_dishes)
                                    selected_meat_types[-1] = '牛肉'
                                else:
                                    # 如果没有菜品，添加一个牛肉菜品，但要确保不超过数量限制
                                    if len(meat_dishes) < meat_count:
                                        meat_dishes.append(random.choice(beef_dishes))
                                        selected_meat_types.append('牛肉')
                                meat_used['牛肉'] = True
                    # 检查鸡肉日
                    elif day_offset == meat_days.get('鸡肉') and not ('鸡肉' in soup_ingredients and meat_used.get('鸡肉', False)):
                        # 如果是鸡肉日但未通过菜品或汤使用鸡肉，强制使用鸡肉
                        if '鸡肉' not in selected_meat_types:
                            # 查找可用的鸡肉菜品
                            chicken_dishes = [d for d in self.dish_categories['荤菜']['鸡肉'] 
                                           if d not in meat_dishes and d not in week_used]
                            if chicken_dishes:
                                # 替换最后一个非鸡肉菜品，确保不超过规定的荤菜数量
                                if len(meat_dishes) > 0:
                                    meat_dishes[-1] = random.choice(chicken_dishes)
                                    selected_meat_types[-1] = '鸡肉'
                                else:
                                    # 如果没有菜品，添加一个鸡肉菜品，但要确保不超过数量限制
                                    if len(meat_dishes) < meat_count:
                                        meat_dishes.append(random.choice(chicken_dishes))
                                        selected_meat_types.append('鸡肉')
                                meat_used['鸡肉'] = True
                
                # 严格控制荤菜数量，确保不超过规定值
                if len(meat_dishes) > meat_count:
                    # 如果超过了数量限制，移除多余的菜品
                    excess = len(meat_dishes) - meat_count
                    meat_dishes = meat_dishes[:-excess]
                    selected_meat_types = selected_meat_types[:-excess]
                
                # 安全检查，避免无限循环
                if len(meat_dishes) > 5:
                    break

            # 选择素菜（根据汤的类型调整数量：荤汤3个，素汤2个）
            if len(self.dish_categories['素菜']) == 0:
                self._add_default_homemade_dishes()

            veg_dishes = []
            veg_count = 3 if soup_is_meat else 2  # 荤汤时3个素菜，素汤时2个素菜
            
            while len(veg_dishes) < veg_count:
                available_veg = [v for v in self.dish_categories['素菜'] 
                                if not self._check_dish_conflict(v, daily_used, daily_ingredients)
                                and v not in veg_dishes
                                and v not in week_used]
                
                if not available_veg:
                    available_veg = [v for v in self.dish_categories['素菜'] 
                                    if v not in veg_dishes
                                    and v not in week_used]
                
                if not available_veg:
                    available_veg = [v for v in self.dish_categories['素菜'] 
                                    if v not in veg_dishes]
                
                if not available_veg:
                    self._add_default_homemade_dishes()
                    available_veg = self.dish_categories['素菜']
                
                veg = random.choice(available_veg)
                veg_dishes.append(veg)

            return meat_dishes, veg_dishes, soup
        except Exception as e:
            print(f"生成午餐出错: {e}")
            return ['红烧肉', '鱼香肉丝'], ['炒青菜', '麻婆豆腐'], '番茄鸡蛋汤'

    def _format_lunch(self, meat_dishes, veg_dishes, soup):
        """格式化午餐描述"""
        all_dishes = meat_dishes + veg_dishes + [soup]
        return ", ".join(all_dishes)

    def save_database_to_excel(self):
        """保存数据库到Excel文件"""
        return self._save_dish_database()


class MenuApp:
    def __init__(self, root):
        self.root = root
        # 在窗口创建后立即设置背景色和标题
        self.root.title("")
        
        # 设置窗口图标，使用优化的兼容性方法
        set_window_icon(self.root)
        
        # 重要：先设置主题样式，再创建任何UI元素
        self._setup_blue_theme()
        
        # 设置窗口背景色为浅蓝色，确保标题栏下方区域也被覆盖
        self.root.configure(bg='#e3f2fd')
        
        # 创建主背景框架（浅蓝色）作为底层，确保铺满整个窗口
        self.main_bg_frame = ttk.Frame(self.root, style='Main.TFrame')
        self.main_bg_frame.pack(fill=tk.BOTH, expand=True, padx=0, pady=0)
        
        # 创建UI
        self._create_widgets()
        
        # 更新窗口以确保所有设置生效
        self.root.update_idletasks()
        
        # 初始化系统，自动加载数据库
        self.system = CanteenMenuSystem()
        
        # 检查是否是首次启动
        self.first_run = not os.path.exists('app_config.ini')
        
        # 初始化数据库状态
        if self.system.db_loaded:
            self.db_status_label.config(text="数据库已加载", foreground="green")
            self.generate_btn.config(state=tk.NORMAL)
            self.download_btn.config(state=tk.NORMAL)
        else:
            self.db_status_label.config(text="数据库加载失败，请手动加载", foreground="red")
            self.generate_btn.config(state=tk.DISABLED)
            self.download_btn.config(state=tk.DISABLED)
        
        if self.first_run:
            # 首次启动提示
            # 设置提示窗口为完全不透明
            result = messagebox.showinfo("提示", "欢迎使用食堂排菜软件！\n已为您自动加载菜品数据库。")
            with open('app_config.ini', 'w') as f:
                f.write('first_run=0')
            self.first_run = False
        
        # 设置默认日期为下周一
        today = datetime.now()
        days_to_next_monday = (7 - today.weekday()) % 7
        if days_to_next_monday == 0:  # 如果今天是周一，默认下周一
            days_to_next_monday = 7
        next_monday = today + timedelta(days=days_to_next_monday)
        self.start_date = next_monday.strftime("%Y-%m-%d")
        self.date_entry.delete(0, tk.END)
        self.date_entry.insert(0, self.start_date)
        
        self.excel_file = '人资食堂菜单.xlsx'
        self.menu_data = None
        self.end_date = None

    def _setup_blue_theme(self):
        """设置统一的天蓝色主题样式"""
        self.style = ttk.Style()
        
        # 主背景样式 - 确保浅蓝色铺满
        self.style.configure('Main.TFrame', background='#e3f2fd')
        
        # 统一标题栏背景色与主背景一致
        self.style.configure('Header.TFrame', background='#e3f2fd')
        
        # 天蓝色主题
        self.style.configure('TFrame', background='#e3f2fd')
        self.style.configure('TLabelframe', background='#e3f2fd', foreground='#0d47a1')
        self.style.configure('TLabelframe.Label', background='#e3f2fd', foreground='#0d47a1', font=('微软雅黑', 10, 'bold'))
        
        # 统一所有标签的字体大小和颜色
        self.style.configure('TLabel', background='#e3f2fd', foreground='#0d47a1', font=('微软雅黑', 10))
        self.style.configure('Header.TLabel', background='#e3f2fd', foreground='#0d47a1', font=('微软雅黑', 24, 'bold'))
        self.style.configure('TEntry', fieldbackground='#ffffff', foreground='#0d47a1', font=('微软雅黑', 10))
        self.style.configure('TSpinbox', fieldbackground='#ffffff', foreground='#0d47a1', font=('微软雅黑', 10))
        
        # 按钮样式
        self.style.configure('TButton', 
                           background='#90caf9',
                           foreground='#0d47a1',
                           font=('微软雅黑', 10),
                           padding=5)
        self.style.map('TButton',
                      background=[('active', '#64b5f6'), ('pressed', '#bbdefb')],
                      foreground=[('active', '#0d47a1'), ('pressed', '#0d47a1')])
        
        # 表格样式 - 设置与主背景一致的颜色
        self.style.configure('Treeview', 
                           background='#e3f2fd', 
                           fieldbackground='#e3f2fd', 
                           foreground='#0d47a1',
                           rowheight=25,
                           font=('微软雅黑', 9))
        self.style.configure('Treeview.Heading', 
                           background='#bbdefb', 
                           foreground='#0d47a1',
                           font=('微软雅黑', 10, 'bold'))
        self.style.map('Treeview', 
                      background=[('selected', '#90caf9')],
                      foreground=[('selected', '#0d47a1')])
        
        # 标签页样式
        self.style.configure('TNotebook', background='#e3f2fd')
        self.style.configure('TNotebook.Tab', 
                           background='#bbdefb',
                           foreground='#0d47a1',
                           font=('微软雅黑', 10, 'bold'),
                           padding=[10, 5])
        self.style.map('TNotebook.Tab',
                      background=[('selected', '#90caf9')],
                      foreground=[('selected', 'black')])
        
        # 底部信息样式
        self.style.configure('Footer.TLabel', 
                           background='#e3f2fd', 
                           foreground='#0d47a1',
                           font=('微软雅黑', 10))

    def _create_widgets(self):
        # 标题栏
        title_frame = ttk.Frame(self.main_bg_frame, style='Header.TFrame')
        title_frame.pack(fill=tk.X, padx=10, pady=5)
        title_frame.pack_propagate(False)
        title_frame.configure(height=100)  # 标题栏高度
        
        # 标题内部框架
        title_inner_frame = ttk.Frame(title_frame, style='Header.TFrame')
        title_inner_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建标题标签，居中显示
        title_label = ttk.Label(title_inner_frame, text="西昌人资自动排菜软件 第三版", style='Header.TLabel')
        title_label.pack(side=tk.TOP, pady=20)  # 标题居中显示
        
        # 参数设置栏
        date_frame = ttk.LabelFrame(self.main_bg_frame, text="参数设置", padding="10", style='TLabelframe')
        date_frame.pack(fill=tk.X, padx=10, pady=5)
        
        # 配置参数栏的布局
        param_frame = ttk.Frame(date_frame, style='TFrame')
        param_frame.pack(fill=tk.X)
        
        # 参数设置栏元素
        ttk.Label(param_frame, text="开始日期:", style='TLabel').pack(side=tk.LEFT, padx=(0,5), pady=5)
        
        today = datetime.now().strftime("%Y-%m-%d")
        self.date_entry = ttk.Entry(param_frame, width=12, style='TEntry')
        self.date_entry.pack(side=tk.LEFT, padx=(0,15), pady=5)
        self.date_entry.insert(0, today)
        
        ttk.Label(param_frame, text="生成周数:", style='TLabel').pack(side=tk.LEFT, padx=(0,5), pady=5)
        
        self.weeks_var = tk.IntVar(value=1)
        weeks_spinbox = ttk.Spinbox(param_frame, from_=1, to=10, textvariable=self.weeks_var, width=5, style='TSpinbox')
        weeks_spinbox.pack(side=tk.LEFT, padx=(0,15), pady=5)
        
        # 数据库状态标签
        self.db_status_label = ttk.Label(param_frame, text="数据库未加载", style='TLabel', foreground="red")
        self.db_status_label.pack(side=tk.LEFT, padx=(0,10), pady=5)
        
        # 加载数据库按钮
        load_db_btn = ttk.Button(param_frame, text="加载菜品数据库", command=self.load_database, style='TButton')
        load_db_btn.pack(side=tk.LEFT, padx=(0,10), pady=5)
        
        self.generate_btn = ttk.Button(param_frame, text="生成菜单", command=self.generate_menu, style='TButton')
        self.generate_btn.pack(side=tk.LEFT, padx=(0,10), pady=5)
        
        self.download_btn = ttk.Button(param_frame, text="下载菜单", command=self.download_menu, style='TButton')
        self.download_btn.pack(side=tk.LEFT, padx=(0,10), pady=5)
        
        # 菜品数据库按钮
        db_btn = ttk.Button(param_frame, text="查看菜品数据库", command=self.show_database, style='TButton')
        db_btn.pack(side=tk.LEFT, padx=(0,10), pady=5)
        
        save_db_btn = ttk.Button(param_frame, text="保存数据库表格", command=self.save_database, style='TButton')
        save_db_btn.pack(side=tk.LEFT, padx=(0,10), pady=5)
        
        # 菜单表格区域
        table_frame = ttk.LabelFrame(self.main_bg_frame, text="生成的菜单【每日无重复及相关菜品，午餐5个菜含汤（荤汤素汤），同一周无重复菜品，牛肉和鸡肉每周各出现一次】", 
                                   padding="10", style='TLabelframe')
        table_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        
        # 创建表格容器
        table_container = ttk.Frame(table_frame, style='TFrame')
        table_container.pack(fill=tk.BOTH, expand=True)
        
        # 创建表格
        columns = ("日期", "星期", "早餐", "午餐", "水果")
        self.tree = ttk.Treeview(table_container, columns=columns, show="headings", style='Treeview')
        
        # 设置列标题和宽度
        self.tree.heading("日期", text="日期")
        self.tree.column("日期", width=100, anchor=tk.CENTER)
        
        self.tree.heading("星期", text="星期")
        self.tree.column("星期", width=80, anchor=tk.CENTER)
        
        self.tree.heading("早餐", text="早餐")
        self.tree.column("早餐", width=200, anchor=tk.W)
        
        self.tree.heading("午餐", text="午餐（5个菜，含汤）")
        self.tree.column("午餐", width=400, anchor=tk.W)
        
        self.tree.heading("水果", text="水果")
        self.tree.column("水果", width=100, anchor=tk.CENTER)
        
        # 添加滚动条
        scrollbar_y = ttk.Scrollbar(table_container, orient=tk.VERTICAL, command=self.tree.yview)
        scrollbar_x = ttk.Scrollbar(table_container, orient=tk.HORIZONTAL, command=self.tree.xview)
        self.tree.configure(yscroll=scrollbar_y.set, xscroll=scrollbar_x.set)
        
        # 放置表格和滚动条
        scrollbar_y.pack(side=tk.RIGHT, fill=tk.Y)
        scrollbar_x.pack(side=tk.BOTTOM, fill=tk.X)
        self.tree.pack(fill=tk.BOTH, expand=True)
        
        # 底部信息框架，使用ttk.Frame确保背景色一致
        footer_frame = ttk.Frame(self.main_bg_frame, style='TFrame', height=40)
        footer_frame.pack(fill=tk.X, padx=8, pady=8)
        footer_frame.pack_propagate(False)
        
        # 创建底部信息内部框架，签名和枫叶图标放在右侧
        footer_inner_frame = ttk.Frame(footer_frame, style='TFrame')
        footer_inner_frame.pack(fill=tk.X, expand=True, padx=1, pady=1)
        
        # 显示签名和枫叶图标在右侧
        signature_frame = ttk.Frame(footer_inner_frame, style='TFrame')
        signature_frame.pack(side=tk.RIGHT)
        
        # 签名文本
        signature_label = ttk.Label(
            signature_frame, 
            text="苏淮 & 晓枫   2025.9.22", 
            style='Footer.TLabel'
        )
        signature_label.pack(side=tk.LEFT, padx=5, pady=5)
        
        # 底部红色枫叶图标（放大1倍，放在日期右边，置于顶层）
        self.footer_maple_label = ttk.Label(signature_frame, style='TLabel', text="🍁", font=("Arial", 20), foreground="#FF0000")
        self.footer_maple_label.pack(side=tk.LEFT, padx=5)
        # 确保枫叶图标显示在最上层
        self.footer_maple_label.lift()

    def load_database(self):
        """手动加载数据库"""
        try:
            # 尝试加载数据库
            success = self.system.load_database()
            
            if success:
                self.db_status_label.config(text="数据库已加载", foreground="green")
                self.generate_btn.config(state=tk.NORMAL)
                self.download_btn.config(state=tk.NORMAL)
                
                # 如果是首次运行，创建配置文件标记
                if self.first_run:
                    with open('app_config.ini', 'w') as f:
                        f.write('first_run=0')
                    self.first_run = False
                
                messagebox.showinfo("成功", "菜品数据库加载成功！")
            else:
                # 尝试创建新的数据库
                self.system._add_default_homemade_dishes()
                self.system._save_dish_database()
                self.system.db_loaded = True
                
                self.db_status_label.config(text="已创建并加载新数据库", foreground="green")
                self.generate_btn.config(state=tk.NORMAL)
                self.download_btn.config(state=tk.NORMAL)
                
                if self.first_run:
                    with open('app_config.ini', 'w') as f:
                        f.write('first_run=0')
                    self.first_run = False
                
                # 设置提示窗口为完全不透明
                result = messagebox.showinfo("提示", "未找到现有数据库，已创建新的默认数据库并加载！")
        except Exception as e:
            self.db_status_label.config(text=f"数据库加载失败: {str(e)}", foreground="red")
            # 设置错误窗口为完全不透明
            result = messagebox.showerror("错误", f"加载数据库时发生错误: {str(e)}")

    def generate_menu(self):
        # 检查数据库是否已加载
        if not self.system.db_loaded:
            # 使用简单的提示框
            messagebox.showinfo("提示", "请先加载菜品数据库！")
            return
            
        # 清空现有数据
        for item in self.tree.get_children():
            self.tree.delete(item)
        
        # 获取输入
        self.start_date = self.date_entry.get()
        weeks = self.weeks_var.get()
        
        try:
            # 生成菜单
            self.menu_data, self.start_date, self.end_date = self.system.generate_menu(self.start_date, weeks)
            
            if self.menu_data is None:
                messagebox.showerror("错误", "生成菜单失败，请确保数据库已正确加载")
                return
                
            # 按照指定表格排版输出，确保列名正确
            try:
                self.menu_data = self.menu_data[['日期', '星期', '早餐', '午餐', '水果']]
            except KeyError:
                # 如果列名不匹配，确保创建正确的列
                missing_cols = []
                for col in ['日期', '星期', '早餐', '午餐', '水果']:
                    if col not in self.menu_data.columns:
                        missing_cols.append(col)
                
                # 创建默认值填充缺失列
                for col in missing_cols:
                    self.menu_data[col] = ''
                
                # 重新排序列
                self.menu_data = self.menu_data[['日期', '星期', '早餐', '午餐', '水果']]
            
            # 填充表格
            for _, row in self.menu_data.iterrows():
                self.tree.insert("", tk.END, values=(
                    row['日期'],
                    row['星期'],
                    row['早餐'],
                    row['午餐'],
                    row['水果']
                ))
                
        except Exception as e:
            # 使用简单的错误对话框
            messagebox.showerror("错误", f"生成菜单失败: {str(e)}")
            # 出错时添加默认菜单
            default_data = []
            current_date = datetime.strptime(self.start_date, '%Y-%m-%d')
            # 确保从周一（0）开始
            if current_date.weekday() != 0:
                days_to_monday = (7 - current_date.weekday()) % 7
                current_date += timedelta(days=days_to_monday)
                
            weekdays = ['周一', '周二', '周三', '周四', '周五']
            for week in range(weeks):
                for i in range(5):
                    day_of_week = weekdays[i]
                    current_day = current_date + timedelta(days=i)
                    default_lunch = random.choice([
                        '蛋炒饭', '青椒肉丝炒饭', '榨菜炒饭', 
                        '扬州炒饭', '火腿蛋炒饭', '老干妈炒饭'
                    ]) if day_of_week == '周五' else '红烧肉, 鱼香肉丝, 炒青菜, 麻婆豆腐, 番茄鸡蛋汤'
                    
                    default_data.append({
                        '日期': current_day.strftime('%Y-%m-%d'),
                        '星期': day_of_week,
                        '早餐': '牛奶, 稀饭, 馒头, 鸡蛋',
                        '午餐': default_lunch,
                        '水果': '时令水果'
                    })
                current_date += timedelta(days=7)  # 移动到下周一
            
            self.menu_data = pd.DataFrame(default_data)
            for _, row in self.menu_data.iterrows():
                self.tree.insert("", tk.END, values=(
                    row['日期'],
                    row['星期'],
                    row['早餐'],
                    row['午餐'],
                    row['水果']
                ))

    def download_menu(self):
        if not self.system.db_loaded:
            # 显示简单的提示信息，不使用图标
            root = tk.Toplevel()
            root.title("提示")
            root.geometry("300x120")
            root.configure(bg='#e3f2fd')
            root.resizable(False, False)
            # 设置窗口图标
            set_window_icon(root)
            
            # 居中窗口
            root.update_idletasks()
            width = root.winfo_width()
            height = root.winfo_height()
            x = (root.winfo_screenwidth() // 2) - (width // 2)
            y = (root.winfo_screenheight() // 2) - (height // 2)
            root.geometry('{}x{}+{}+{}'.format(width, height, x, y))
            
            # 提示信息标签
            info_label = ttk.Label(root, text="请先加载菜品数据库！", style='TLabel')
            info_label.pack(padx=20, pady=20)
            
            # 确定按钮
            ok_button = ttk.Button(root, text="确定", command=root.destroy, style='TButton')
            ok_button.pack(pady=10)
            
            # 等待用户关闭窗口
            root.wait_window()
            return
            
        if self.menu_data is None:
            # 设置警告窗口为完全不透明
            result = messagebox.showwarning("警告", "请先生成菜单")
            return
        
        try:
            # 格式化日期用于表头
            start_dt = datetime.strptime(self.start_date, '%Y-%m-%d')
            end_dt = datetime.strptime(self.end_date, '%Y-%m-%d')
            
            start_str = start_dt.strftime('%Y年%m月%d日')
            end_str = end_dt.strftime('%Y年%m月%d日')
            
            # 表头
            header_text = f"西昌人力资源开发有限公司{start_str}~{end_str}菜单"
            
            # 默认保存路径为脚本所在目录
            script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
            default_filename = f"{start_dt.strftime('%Y%m%d')}-{end_dt.strftime('%Y%m%d')}菜单.xlsx"
            default_path = os.path.join(script_dir, default_filename)
            
            file_path = filedialog.asksaveasfilename(
                defaultextension=".xlsx",
                filetypes=[("Excel文件", "*.xlsx"), ("所有文件", "*.*")],
                title="保存菜单",
                initialdir=script_dir,
                initialfile=default_filename
            )
            
            # 如果用户取消选择，使用默认路径
            if not file_path:
                file_path = default_path
            
            # 创建边框样式
            thin_border = Border(
                left=Side(style='thin'),
                right=Side(style='thin'),
                top=Side(style='thin'),
                bottom=Side(style='thin')
            )
            
            # 使用ExcelWriter写入
            with pd.ExcelWriter(file_path, engine='openpyxl') as writer:
                # 先打印菜单数据到控制台，用于检查
                print("\n\n生成的菜单数据：")
                print(self.menu_data)
                
                # 写入数据，从第2行开始
                self.menu_data.to_excel(writer, index=False, sheet_name='菜单', startrow=1)
                
                worksheet = writer.sheets['菜单']
                
                # 设置标题：第一行，合并A到E列
                worksheet.merge_cells(start_row=1, start_column=1, end_row=1, end_column=5)
                title_cell = worksheet.cell(row=1, column=1)
                title_cell.value = header_text
                title_cell.font = Font(bold=True, size=16)
                title_cell.alignment = Alignment(horizontal='center', vertical='center')
                
                # 设置列宽
                column_widths = {
                    1: 12,  # A列：日期
                    2: 10,  # B列：星期
                    3: 33,  # C列：早餐
                    4: 62,  # D列：午餐
                    5: 15   # E列：水果
                }
                
                for col, width in column_widths.items():
                    col_letter = get_column_letter(col)
                    worksheet.column_dimensions[col_letter].width = width
                
                # 添加列标题行样式
                header_row = 2
                for col in range(1, 6):
                    cell = worksheet.cell(row=header_row, column=col)
                    cell.font = Font(bold=True)
                    cell.alignment = Alignment(horizontal='center', vertical='center')
                    cell.border = thin_border
                
                # 为数据行添加边框
                for row in range(3, worksheet.max_row + 1):
                    for col in range(1, 6):
                        cell = worksheet.cell(row=row, column=col)
                        if cell.value:
                            cell.border = thin_border
            
            # 显示保存成功提示，设置为完全不透明
            result = messagebox.showinfo("成功", f"菜单已保存到:\n{file_path}")
        except Exception as e:
            # 设置错误窗口为完全不透明
            result = messagebox.showerror("错误", f"保存菜单失败: {str(e)}")

    def show_database(self):
        if not self.system.db_loaded:
            messagebox.showinfo("提示", "请先加载菜品数据库！")
            return
            
        # 创建新窗口显示菜品数据库
        db_window = tk.Toplevel(self.root)
        db_window.title("菜品数据库")
        db_window.geometry("900x600")
        db_window.configure(bg='#e3f2fd')  # 设置子窗口背景色与主窗口一致
        db_window.minsize(800, 500)
        # 设置窗口图标
        set_window_icon(db_window)
        # 设置窗口为不透明
        db_window.attributes('-alpha', 1.0)
        
        # 创建标签页
        notebook = ttk.Notebook(db_window, style='TNotebook')
        notebook.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 早餐标签页
        breakfast_frame = ttk.Frame(notebook, style='TFrame')
        notebook.add(breakfast_frame, text="早餐")
        
        # 自动加载早餐数据
        self._load_breakfast_data(breakfast_frame)
        
        # 荤菜标签页
        meat_frame = ttk.Frame(notebook, style='TFrame')
        notebook.add(meat_frame, text="荤菜")
        
        # 自动加载荤菜数据
        self._load_meat_data(meat_frame)
        
        # 素菜标签页
        veg_frame = ttk.Frame(notebook, style='TFrame')
        notebook.add(veg_frame, text="素菜")
        
        # 自动加载素菜数据
        self._load_veg_data(veg_frame)
        
        # 汤类标签页
        soup_frame = ttk.Frame(notebook, style='TFrame')
        notebook.add(soup_frame, text="汤类")
        
        # 自动加载汤类数据
        self._load_soup_data(soup_frame)
        
        # 水果标签页
        fruit_frame = ttk.Frame(notebook, style='TFrame')
        notebook.add(fruit_frame, text="水果")
        
        # 自动加载水果数据
        self._load_fruit_data(fruit_frame)
        
        # 简餐标签页
        simple_meal_frame = ttk.Frame(notebook, style='TFrame')
        notebook.add(simple_meal_frame, text="简餐")
        
        # 自动加载简餐数据
        self._load_simple_meal_data(simple_meal_frame)

    def _create_category_frame(self, parent, category):
        """创建分类框架，自动加载数据"""
        frame = ttk.Frame(parent, style='TFrame')
        frame.pack(fill=tk.BOTH, expand=True)
        
        return frame

    def _load_breakfast_data(self, parent):
        """加载早餐数据"""
        frame = self._create_category_frame(parent, "早餐")
        
        # 创建树状图
        columns = ("主食", "饮品", "其他", "米粉")
        tree = ttk.Treeview(frame, columns=columns, show="headings", style='Treeview')
        for col in columns:
            tree.heading(col, text=col)
            tree.column(col, width=200, anchor=tk.W)
        
        # 填充数据
        max_len = max(len(self.system.dish_categories['早餐']['主食']),
                      len(self.system.dish_categories['早餐']['饮品']),
                      len(self.system.dish_categories['早餐']['其他']),
                      len(self.system.dish_categories['早餐']['米粉']))
        
        for i in range(max_len):
            staple = self.system.dish_categories['早餐']['主食'][i] if i < len(self.system.dish_categories['早餐']['主食']) else ""
            drink = self.system.dish_categories['早餐']['饮品'][i] if i < len(self.system.dish_categories['早餐']['饮品']) else ""
            other = self.system.dish_categories['早餐']['其他'][i] if i < len(self.system.dish_categories['早餐']['其他']) else ""
            rice_noodle = self.system.dish_categories['早餐']['米粉'][i] if i < len(self.system.dish_categories['早餐']['米粉']) else ""
            tree.insert("", tk.END, values=(staple, drink, other, rice_noodle))
        
        scroll_y = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=tree.yview)
        scroll_x = ttk.Scrollbar(frame, orient=tk.HORIZONTAL, command=tree.xview)
        tree.configure(yscroll=scroll_y.set, xscroll=scroll_x.set)
        
        scroll_y.pack(side=tk.RIGHT, fill=tk.Y)
        scroll_x.pack(side=tk.BOTTOM, fill=tk.X)
        tree.pack(fill=tk.BOTH, expand=True)
        
        return tree

    def _load_meat_data(self, parent):
        """加载荤菜数据"""
        frame = self._create_category_frame(parent, "荤菜")
        
        # 创建树状图
        columns = ("猪肉", "牛肉", "鸡肉")
        tree = ttk.Treeview(frame, columns=columns, show="headings", style='Treeview')
        for col in columns:
            tree.heading(col, text=col)
            tree.column(col, width=280, anchor=tk.W)
        
        # 填充数据
        max_len = max(len(self.system.dish_categories['荤菜']['猪肉']),
                      len(self.system.dish_categories['荤菜']['牛肉']),
                      len(self.system.dish_categories['荤菜']['鸡肉']))
        
        for i in range(max_len):
            pork = self.system.dish_categories['荤菜']['猪肉'][i] if i < len(self.system.dish_categories['荤菜']['猪肉']) else ""
            beef = self.system.dish_categories['荤菜']['牛肉'][i] if i < len(self.system.dish_categories['荤菜']['牛肉']) else ""
            chicken = self.system.dish_categories['荤菜']['鸡肉'][i] if i < len(self.system.dish_categories['荤菜']['鸡肉']) else ""
            tree.insert("", tk.END, values=(pork, beef, chicken))
        
        scroll_y = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=tree.yview)
        scroll_x = ttk.Scrollbar(frame, orient=tk.HORIZONTAL, command=tree.xview)
        tree.configure(yscroll=scroll_y.set, xscroll=scroll_x.set)
        
        scroll_y.pack(side=tk.RIGHT, fill=tk.Y)
        scroll_x.pack(side=tk.BOTTOM, fill=tk.X)
        tree.pack(fill=tk.BOTH, expand=True)
        
        return tree

    def _load_veg_data(self, parent):
        """加载素菜数据"""
        frame = self._create_category_frame(parent, "素菜")
        
        # 创建树状图
        tree = ttk.Treeview(frame, columns=("素菜",), show="headings", style='Treeview')
        tree.heading("素菜", text="素菜")
        tree.column("素菜", width=850, anchor=tk.W)
        
        # 填充数据
        for item in self.system.dish_categories['素菜']:
            tree.insert("", tk.END, values=(item,))
        
        scroll_y = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=tree.yview)
        scroll_x = ttk.Scrollbar(frame, orient=tk.HORIZONTAL, command=tree.xview)
        tree.configure(yscroll=scroll_y.set, xscroll=scroll_x.set)
        
        scroll_y.pack(side=tk.RIGHT, fill=tk.Y)
        scroll_x.pack(side=tk.BOTTOM, fill=tk.X)
        tree.pack(fill=tk.BOTH, expand=True)
        
        return tree

    def _load_soup_data(self, parent):
        """加载汤类数据"""
        frame = self._create_category_frame(parent, "汤类")
        
        # 创建树状图
        columns = ("荤汤", "素汤")
        tree = ttk.Treeview(frame, columns=columns, show="headings", style='Treeview')
        for col in columns:
            tree.heading(col, text=col)
            tree.column(col, width=420, anchor=tk.W)
        
        # 填充数据
        max_soup_len = max(len(self.system.dish_categories['汤类']['荤汤']),
                           len(self.system.dish_categories['汤类']['素汤']))
        
        for i in range(max_soup_len):
            meat_soup = self.system.dish_categories['汤类']['荤汤'][i] if i < len(self.system.dish_categories['汤类']['荤汤']) else ""
            veg_soup = self.system.dish_categories['汤类']['素汤'][i] if i < len(self.system.dish_categories['汤类']['素汤']) else ""
            tree.insert("", tk.END, values=(meat_soup, veg_soup))
        
        scroll_y = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=tree.yview)
        scroll_x = ttk.Scrollbar(frame, orient=tk.HORIZONTAL, command=tree.xview)
        tree.configure(yscroll=scroll_y.set, xscroll=scroll_x.set)
        
        scroll_y.pack(side=tk.RIGHT, fill=tk.Y)
        scroll_x.pack(side=tk.BOTTOM, fill=tk.X)
        tree.pack(fill=tk.BOTH, expand=True)
        
        return tree

    def _load_fruit_data(self, parent):
        """加载水果数据"""
        frame = self._create_category_frame(parent, "水果")
        
        # 创建树状图
        tree = ttk.Treeview(frame, columns=("水果",), show="headings", style='Treeview')
        tree.heading("水果", text="水果")
        tree.column("水果", width=850, anchor=tk.W)
        
        # 填充数据
        for item in self.system.dish_categories['水果']:
            tree.insert("", tk.END, values=(item,))
        
        scroll_y = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=tree.yview)
        scroll_x = ttk.Scrollbar(frame, orient=tk.HORIZONTAL, command=tree.xview)
        tree.configure(yscroll=scroll_y.set, xscroll=scroll_x.set)
        
        scroll_y.pack(side=tk.RIGHT, fill=tk.Y)
        scroll_x.pack(side=tk.BOTTOM, fill=tk.X)
        tree.pack(fill=tk.BOTH, expand=True)
        
        return tree

    def _load_simple_meal_data(self, parent):
        """加载简餐数据"""
        frame = self._create_category_frame(parent, "简餐")
        
        # 创建树状图
        tree = ttk.Treeview(frame, columns=("简餐",), show="headings", style='Treeview')
        tree.heading("简餐", text="简餐")
        tree.column("简餐", width=850, anchor=tk.W)
        
        # 填充数据
        for item in self.system.dish_categories['简餐']:
            tree.insert("", tk.END, values=(item,))
        
        scroll_y = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=tree.yview)
        scroll_x = ttk.Scrollbar(frame, orient=tk.HORIZONTAL, command=tree.xview)
        tree.configure(yscroll=scroll_y.set, xscroll=scroll_x.set)
        
        scroll_y.pack(side=tk.RIGHT, fill=tk.Y)
        scroll_x.pack(side=tk.BOTTOM, fill=tk.X)
        tree.pack(fill=tk.BOTH, expand=True)
        
        return tree

    def save_database(self):
        if not self.system.db_loaded:
            messagebox.showinfo("提示", "请先加载菜品数据库！")
            return
            
        """保存数据库到Excel文件"""
        try:
            # 确保保存前移除通用"炒饭"
            if '简餐' in self.system.dish_categories:
                self.system.dish_categories['简餐'] = [
                    item for item in self.system.dish_categories['简餐'] 
                    if item != '炒饭'
                ]
            
            # 保留用户添加的所有水果
            if not self.system.dish_categories['水果']:
                self.system.dish_categories['水果'] = ['时令水果']
            
            excel_success = self.system.save_database_to_excel()
            
            if excel_success:
                messagebox.showinfo("成功", 
                                   f"数据库已保存到:\n"
                                   f"{self.system.dish_database_file}")
            else:
                messagebox.showerror("失败", "保存数据库失败，请检查权限或文件是否被占用")
        except Exception as e:
            messagebox.showerror("错误", f"保存数据库时发生错误: {str(e)}")


def set_window_icon(window):
    """优化窗口图标设置，确保主窗口图标能正确加载，解决白色图标问题"""
    try:
        import sys
        import os
        
        # 获取当前脚本所在目录
        script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
        
        # 支持的图标文件列表和优先级
        icon_paths = [
            os.path.join(script_dir, 'favicon.ico'),
            os.path.join(script_dir, 'logo.ico'),
            os.path.join(script_dir, 'favicon.png'),
            os.path.join(script_dir, 'logo.png')
        ]
        
        # 快速检查图标文件是否存在，避免不必要的处理
        icon_path = None
        for path in icon_paths:
            if os.path.exists(path):
                icon_path = path
                break
        
        if not icon_path:
            print("未找到图标文件")
            return
        
        # 对于Windows系统特殊优化，优先使用iconbitmap快速设置任务栏和窗口图标
        is_windows = sys.platform.startswith('win')
        if is_windows and icon_path.lower().endswith('.ico'):
            try:
                # 设置窗口图标，使用default参数确保同时设置任务栏图标
                window.iconbitmap(default=icon_path)
                # 强制刷新窗口以确保图标立即显示
                window.update_idletasks()
            except Exception as e:
                print(f"使用iconbitmap设置图标失败: {e}")
        
        # 尝试使用PIL库进一步优化窗口图标显示
        try:
            from PIL import Image, ImageTk, ImageFile
            # 允许加载大图像时截断处理
            ImageFile.LOAD_TRUNCATED_IMAGES = True
            
            # 加载图标
            icon = Image.open(icon_path)
            
            # 确保有alpha通道支持透明度
            if icon.mode != 'RGBA':
                icon = icon.convert('RGBA')
            
            # 减少尺寸数量，只保留最常用的几个尺寸以提高加载速度
            # 重点包含适合任务栏的尺寸(32-64px)
            standard_sizes = [32, 64, 128]  # 减少到3个核心尺寸
            
            # 获取适合窗口的最佳尺寸
            icon_photos = []
            base_width, base_height = icon.size
            
            # 预先计算调整比例，避免重复计算
            for size in standard_sizes:
                try:
                    # 按比例调整图标大小
                    if base_width > base_height:
                        new_width = size
                        new_height = int(base_height * (size / base_width))
                    else:
                        new_height = size
                        new_width = int(base_width * (size / base_height))
                    
                    # 使用LANCZOS滤镜保证高质量缩放
                    resized_icon = icon.resize((new_width, new_height), Image.LANCZOS)
                    
                    # 创建PhotoImage对象
                    photo = ImageTk.PhotoImage(resized_icon)
                    icon_photos.append(photo)
                except Exception as e:
                    print(f"创建{size}x{size}图标时出错: {e}")
            
            if icon_photos:
                # 设置窗口图标，提供多个尺寸以确保在不同位置显示清晰
                window.iconphoto(True, *icon_photos)
                
                # 保存所有引用防止被垃圾回收
                window._icon_photos = icon_photos
                
                # 强制刷新窗口以确保图标立即显示
                window.update_idletasks()
        except ImportError:
            # PIL库不可用，已在前面使用标准方法尝试设置
            pass
        except Exception as e:
            print(f"处理图标时出错: {e}")
    except Exception as e:
        print(f"设置窗口图标时发生错误: {e}")
        # 出错时静默失败，不影响程序运行

if __name__ == "__main__":
    # 确保中文显示正常
    # 先创建窗口但保持隐藏
    root = tk.Tk()
    root.withdraw()  # 临时隐藏窗口
    
    # 设置窗口图标
    set_window_icon(root)
    
    # 创建应用实例，完成所有UI设置
    app = MenuApp(root)
    
    # 所有设置完成后显示窗口
    root.deiconify()  # 显示窗口
    root.mainloop()
